package com.league.zjxn.main.mine

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.MotionEvent
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.KeyboardUtils
import com.league.zjxn.R
import com.league.zjxn.jetpack.vmodel.AccessViewModel
import com.module.lemlin.owner.OwnerViewModeFragment
import kotlinx.android.synthetic.main.fragment_account_code.*
import java.util.concurrent.TimeUnit

class AccountCodeFragment : OwnerViewModeFragment<AccessViewModel>() {

    companion object {

        private val ARRAY_CODE: Array<String?> = arrayOfNulls(6)

        fun newInstance(): AccountCodeFragment {
            return AccountCodeFragment()
        }
    }

    override val layoutResId: Int
        get() = R.layout.fragment_account_code

    override fun viewModel(): AccessViewModel {
        return createViewModel(requireActivity())
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun initView() {


        with(etAccountCodeContent) {
            isLongClickable = false
            setTextIsSelectable(false)
            setOnClickListener {
                setSelection(text.length)
                isCursorVisible = false
            }
            setOnTouchListener { _, event ->
                if (event.action == MotionEvent.ACTION_UP) {
                    setSelection(text.length)
                    isCursorVisible = false
                }
                return@setOnTouchListener false
            }
        }

        etAccountCodeContent.addTextChangedListener { editable ->
            fillDataCode(code = editable?.toString() ?: "")
            editable?.let { viewModel.mMapSettingPhone["code"] = it.toString() }
            tvAccountCodeSubmit.isEnabled = editable?.length == ARRAY_CODE.size
        }

    }

    override fun initViewMode() {

    }

    override fun initData() {
        KeyboardUtils.showSoftInput(etAccountCodeContent)
    }

    /**
     * 设置验证码数据
     * */
    private fun fillDataCode(code: CharSequence) {
        val length: Int = code.length
        for (i: Int in (if (length == 0) 0 else length - 1)
                until ARRAY_CODE.size) {
            ARRAY_CODE[i] = null
        }
        for (i: Int in 0 until length) {
            ARRAY_CODE[i] = code.toList()[i].toString()
        }
        if (length != 0) {
            ARRAY_CODE[length - 1] = code.last().toString()
        }
        tvAccountCodeCheckCode1.text = ARRAY_CODE[0]
        tvAccountCodeCheckCode2.text = ARRAY_CODE[1]
        tvAccountCodeCheckCode3.text = ARRAY_CODE[2]
        tvAccountCodeCheckCode4.text = ARRAY_CODE[3]
        tvAccountCodeCheckCode5.text = ARRAY_CODE[4]
        tvAccountCodeCheckCode6.text = ARRAY_CODE[5]

        if (code.length == 6) {
            KeyboardUtils.hideSoftInput(etAccountCodeContent)
        }
    }


}